<?php

namespace App\Http\Controllers\Api;

use App\Http\Model\ResponseResult;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Passport\Http\Controllers\HandlesOAuthErrors;
use Laravel\Passport\Token;
use League\OAuth2\Server\AuthorizationServer;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response as Psr7Response;

class AuthController extends Controller
{
    use HandlesOAuthErrors;

    /**
     * The authorization server.
     *
     * @var \League\OAuth2\Server\AuthorizationServer
     */
    protected $server;

    public function __construct(AuthorizationServer $server)
    {
        $this->server = $server;
    }

    /**
     * @param ServerRequestInterface $request
     * @return \Illuminate\Http\Response|\Psr\Http\Message\ResponseInterface
     */
    public function token(ServerRequestInterface $request)
    {
        return $this->withErrorHandling(function () use ($request) {
            return $this->server->respondToAccessTokenRequest($request, new Psr7Response());
        });
    }

    public function destroy(Request $request)
    {
        $this->validator($request, ['client_id' => 'required|integer|exists:oauth_clients,id']);
        if (Token::where('user_id', \Auth::id())->where('client_id', $request->get('client_id'))->delete()) {
            return ResponseResult::success(__('app.logout.success'));
        }
        return ResponseResult::error(1000, __('app.logout.fail'));
    }

    public function login()
    {
        
    }
}
